//
//  RechargeCashVC.swift
//  XiaoJingMallSwift
//
//  Created by beisheng03 on 2017/9/7.
//  Copyright © 2017年 beisheng. All rights reserved.
//

import UIKit
import SVProgressHUD

class RechargeCashVC: BaseViewController {
    
    var payment_list : [PaymentListModel]?
    
    var isMerchant = false
    
    
    var pdrAmount = "0"
    
    var payWay  = "wxpay_app"
    
    lazy var tableView : UITableView = {
        
        let tabV = UITableViewController(style: .plain)
        
        tabV.tableView.delegate = self
        tabV.tableView.dataSource = self
        tabV.tableView.showsVerticalScrollIndicator = false
        tabV.tableView.showsHorizontalScrollIndicator = false
        tabV.tableView.allowsSelection = true
        
        tabV.tableView.frame = self.view.bounds
        
        self.view.addSubview(tabV.tableView)
        
        self.addChildViewController(tabV)
        
        
        return tabV.tableView
        
    }()
    
    
    

    
    
    lazy var bottomView : OrderBottomView = {
        
        let temp : OrderBottomView = Bundle.main.loadNibNamed(self.StringFromClass(classType: OrderBottomView.self), owner: nil, options: nil)?.first as! OrderBottomView
        
        temp.frame = CGRect(x: 0, y: 0, width: KScreenW, height: 118)
        
        temp.btn.setTitle("确认充值", for: .normal)
        
        temp.isHidden = true
        
        temp.delegate = self
        
        return temp
        
    }()

    override func viewDidLoad() {
        super.viewDidLoad()
        
        navigationItem.title = "账户充值"
        
        tableView.tableFooterView = bottomView
        
        tableView.register(UINib(nibName: StringFromClass(classType: OrderSureSetionView.self), bundle: nil), forHeaderFooterViewReuseIdentifier: OrderSureSetionView.identifer())
        
        
        
        tableView.register(UINib(nibName: StringFromClass(classType: OrderSelectCell.self), bundle: nil), forCellReuseIdentifier: OrderSelectCell.identifer())

        tableView.register(UINib(nibName: StringFromClass(classType: RechargeCashFieldCell.self), bundle: nil), forCellReuseIdentifier: RechargeCashFieldCell.identifer())

        
        
        let NotifyChatMsgRecv = NSNotification.Name(rawValue:"KQDidPaySuccess")
        
        NotificationCenter.default.addObserver(forName: NotifyChatMsgRecv, object: nil, queue: OperationQueue.main) { (notice) in
            
            
            self.navigationController?.popViewController(animated: true)
            
            QL1("快钱支付成功")
            
        }
        
        
        
        weak var weakSelf = self
        tableView.mj_header =  ZMRefreshHeader.init {
            
            weakSelf!.loadData()
            
        }
        
        tableView.mj_header.beginRefreshing()


    }
    
    
    override func viewWillDisappear(_ animated: Bool) {
        
        super.viewWillDisappear(animated)
        
        view.endEditing(true)
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    

    
}




extension RechargeCashVC{
    
    func loadData(){
        

        
        NetworkTools.shared.sendRequest(method: .GET_METHOD, pathStr: "mobile/index.php?c=payment&a=payment_list", parameters: nil) { [weak self] (responseObject, error)in
            
            if error == nil {
                
                self?.payment_list = [PaymentListModel]()
                
                
                for dic in responseObject!["datas"]!["list"] as! [[String : AnyObject]]{
                    
                    self?.payment_list!.append(PaymentListModel(dic: dic))
                    
                }
                
                self?.payment_list?.first?.isSelect = true
                
                
                self?.tableView.mj_header.endRefreshing()
                
                self?.tableView.reloadData()
                
                self?.bottomView.isHidden = false
                
            }else{
                
                self?.tableView.mj_header.endRefreshing()
                
                SVProgressHUD.showError(withStatus: error?.domain)
                
            }
        }
    }
}





extension RechargeCashVC{
    
    
    override func numberOfSections(in tableView: UITableView) -> Int {
        
        if payment_list == nil{
            
            return 0
        }
        
        return 2
        
    }
    
    
    
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        if payment_list == nil{
            
            return 0
        }
        
        switch section {
        case 0:
            return payment_list?.count ?? 0
        default:
            return 1
        }
        
    }
    
    
    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        var tableCell : UITableViewCell? = nil
        
        if indexPath.section == 0 {
            
            let tempCell : OrderSelectCell =  tableView.dequeueReusableCell(withIdentifier: OrderSelectCell.identifer()) as! OrderSelectCell
            
            tempCell.model = payment_list?[indexPath.row]
            
            tempCell.models = payment_list
            
            tableCell = tempCell
            
            
        }else{
            
            
            let tempCell : RechargeCashFieldCell =  tableView.dequeueReusableCell(withIdentifier: RechargeCashFieldCell.identifer()) as! RechargeCashFieldCell
            
            tempCell.delegate = self
            
            tableCell = tempCell
            
            
            
        }
        
        
        
        
        return tableCell!
    }
    
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        
        if indexPath.section == 0 {
            return  72
        }else{
            
            return 46
        }
        
    }
    
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        
        
        return 36
        
    }
    
    
    
    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
        
        
        
    }
    
    
    
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        
        
        let temp = tableView.dequeueReusableHeaderFooterView(withIdentifier: OrderSureSetionView.identifer()) as! OrderSureSetionView
        
        if section == 0 {
            
            temp.section = 99
            
        } else {
            
            temp.section = 100
            
        }
        
        
        return temp
        
        
        
    }
    
    
    
    
    
    
    
    
}











extension RechargeCashVC : OrderBottomViewDeleage{
    
    
    func orderBottomViewBtnDidTap(){
        
        view.endEditing(true)
        
        if pdrAmount.characters.count < 1{
        
            alert(str: "请输入充值金额")
        
            return
        }
        
        
        let bubu = Float(pdrAmount) ?? 0
        
        if bubu > 0 {
            
        }else{
        
            alert(str: "请输入有效充值金额")

            return
        }
        
        
        
        var parmeter  = [String : AnyObject]()
        

        for item in payment_list! {
            if item.isSelect == true {
                parmeter["payment_code"] = item.payment_code as AnyObject
                payWay = item.payment_code
            }
        }
        
        if isMerchant == true {
            
            parmeter["is_merchant"] = "1" as AnyObject

        }
        
        
        parmeter["pdr_amount"] = pdrAmount as AnyObject
        
        
        
        NetworkTools.shared.sendRequest(method: .POST_METHOD, pathStr: "mobile/index.php?c=member_buy&a=recharge", parameters: parmeter) { [weak self] (responseObject, error) in
            
            if error == nil{
            
                if self?.payWay == "alipay_app"{
                    
                    let aliPayStr = responseObject?["datas"]?["orderString"]
                    
                    if aliPayStr != nil{
                        
                        self?.AliPay(payStr: aliPayStr! as! String)
                        
                    }
                    
                    
                    
                }else if self?.payWay == "wxpay_app"{
                    
                    let WXPayDic = responseObject?["datas"]?["wxpay_param"]
                    
                    if WXPayDic != nil{
                        
                        
                        self?.WXPay(dic: WXPayDic! as! [String : AnyObject])
                        
                        
                    }
                    
                    
                }else{
                    
                    
                    let KQPayStr = responseObject?["datas"]?["orderString"]
                    
                    if KQPayStr != nil{
                        
                        self?.KQPay(payStr: KQPayStr! as! String)
                        
                    }
                    
            }
                
                
        }else{
                
                
                
                SVProgressHUD.showError(withStatus: error?.domain)
   
                
            }


    
    QL1("确认充值")
    
    }
        
        
  

  
}
    
    
    
    
    
    
    func alert(str : String) {
        
        let tempVC = UIAlertController(title: nil, message: str, preferredStyle: .alert)
        
        let action1 = UIAlertAction(title: "确定", style: .destructive) { (action) in
            
        }
        
        
        
        let action2 = UIAlertAction(title: "取消", style: .default) { (action) in
            
            
        }
        
        tempVC.addAction(action2)
        tempVC.addAction(action1)
        
        present(tempVC, animated: true, completion: nil)
        
        
    }
    
    
    
    
    
    
    
    
    func AliPay(payStr : String){
        
        
        AlipaySDK.defaultService().payOrder(payStr, fromScheme: "com.xiaojing.mall") { (_) in
            
        }
        
        
        
    }
    
    
    func WXPay(dic : [String : AnyObject]) {
        
        let temp  = PayReq()
        
        //由用户微信号和AppID组成的唯一标识，用于校验微信用户
        temp.openID = dic["appid"] as! String
        
        // 商家id，在注册的时候给的
        temp.partnerId = dic["partnerid"] as! String
        
        // 预支付订单这个是后台跟微信服务器交互后，微信服务器传给你们服务器的，你们服务器再传给你
        temp.prepayId  = dic["prepayid"] as! String
        
        // 根据财付通文档填写的数据和签名
        //这个比较特殊，是固定的，只能是即req.package = Sign=WXPay
        temp.package   = dic["pkg"] as! String
        
        // 随机编码，为了防止重复的，在后台生成
        temp.nonceStr  = dic["noncestr"] as! String
        
        // 这个是时间戳，也是在后台生成的，为了验证支付的
        let str = dic["timestamp"] as! String
        
        let temUin = UInt32(str)
        
        if temUin != nil {
            
            temp.timeStamp = temUin!
            
        }
        
        
        // 这个签名也是后台做的
        temp.sign = dic["sign"] as! String
        
        //发送请求到微信，等待微信返回onResp
        
        WXApi.send(temp)
        
        
        
    }
    
    
    func KQPay(payStr : String) {
        
        let temp = GoodsDetailController()
        
        temp.urlStr = payStr
        
        temp.hiddenBar = false
        
        temp.navigationItem.title = "快钱收银台"

        
        navigationController?.pushViewController(temp, animated: true)
        
        
        
    }
    
    



}
